package view;

import cmd.Cmd_ChangeLayerColors;
import tool.PixelTool;
import hxd.App;
import tree.Root;
import hxd.File;
import hl.UI;
import cmd.Cmd_StopAutoPlay;
import cmd.Cmd;
import cmd.Cmd_StartAutoPlay;
import tree.LeafKind;
import h2d.domkit.Object;
import h2d.Flow;
import view.UICompents;

@:uiComp("view-menu")
class ViewMenuComp extends Flow implements Object{
    static var SRC =
    <view-menu>
        <button("新建") public id = "btn_new"/>
        <button("保存") public id = "btn_save"/>
        <button("加载") public id = "btn_load"/> 
        <button("画布") public id = "btn_canvas"/>
        <button("播放") public id = "btn_play"/>
        <button("Test") public id = "btn_test"/>
    </view-menu>

    public function new(?parent) {
		super(parent);
		initComponent();
	}
}

class View_Menu extends ViewTress<ViewMenuComp>{
    public function new(?view : ViewMenuComp) {
        super(ViewMenuComp, view);
    }

    public override function OnEnter(last:LeafKind) {
        super.OnEnter(last);
        m_view.btn_play.onClick = function() {
            if(data_canvas.isAutoPlay){
                var cmd = new Cmd_StopAutoPlay(this);
                root_cmd.AddCmd(cmd);
            }
            else {
               var cmd = new Cmd_StartAutoPlay(this);
               root_cmd.AddCmd(cmd);
            }
        };

        m_view.btn_save.onClick = function () {
            root_data.SaveData();

        };

        m_view.btn_load.onClick = function () {
            root_data.LoadData();
        };

        m_view.btn_test.onClick = function() {
            File.browse(function(e) {
                if(e == null || e.fileName == null || e.fileName == ""){
                    return;
                }
                var bytes = sys.io.File.getBytes(e.fileName);
                var any = hxd.res.Any.fromBytes(e.fileName, bytes);
                var pixels = any.toImage().getPixels();
                var colors = PixelTool.PixelToColors(pixels, data_canvas.width, data_canvas.height);
                pixels.dispose();
                var layer = data_canvas.curLayer;
                var cmd = new Cmd_ChangeLayerColors(layer, colors);
                root_cmd.AddCmd(cmd);
            });

        }
        
    }
}